package UIFree.controls.base
{
	import UIFree.CLoader;
	import UIFree.uif_component;
	import UIFree.uif_ecomponent;
	
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.system.LoaderContext;

	public class uif_source extends uif_ecomponent {
		protected var _source		: CLoader;
		protected var _imageSize	: Point;
		public function uif_source(parent:uif_component, ax:int=0, ay:int=0, awidth:int=0, aheight:int=0, styleClass:String='') {
			super(parent, ax, ay, awidth, aheight, styleClass);
			
			_imageSize = new Point();
			var inner: Rectangle = getInner();
			_source = new CLoader(this, '', doLoad, inner.x, inner.y, new LoaderContext(true));
		}
		
		override public function dispose():void {
			_source.unload();
			super.dispose();
		}
		
		protected function doLoad(e: Event): void {
			_imageSize = new Point(_source.contentLoaderInfo.width, _source.contentLoaderInfo.height);
			centeredSource();
		}
		
		protected function centeredSource(): void {
			if (_source) {
				var coordinates: Rectangle = EnterHere(_imageSize);
				var mat: Matrix = new Matrix();
				mat.scale(coordinates.width / _imageSize.x, coordinates.height / _imageSize.y);
				mat.translate(coordinates.x, coordinates.y);
				_source.transform.matrix = mat;
			}
		}
				
		public function get sourceScale(): Number {
			return _source.scaleX;
		}
		
		public function get source(): CLoader {
			return _source;
		}
		
		public function get imageSize(): Point {
			return _imageSize;
		}
		
		public function loadSource(url: String, onComplete: Function=null): void {
			if (url) {
				if (_source.contentLoaderInfo.bytesLoaded > 0) _source.unload();
	
				var request: URLRequest = new URLRequest(url);
/*				var refererHeader: URLRequestHeader = new URLRequestHeader('Referer',  stage.loaderInfo.url);
				request.requestHeaders.push(refererHeader);*/
				_source.load(request, new LoaderContext(true));
				if (onComplete != null) {
					function doSourceLoad(e: Event): void {
						_source.contentLoaderInfo.removeEventListener(Event.COMPLETE, doSourceLoad);
						onComplete(e);
					}
					_source.contentLoaderInfo.addEventListener(Event.COMPLETE, doSourceLoad);
				}
			}
		}
	}

}